package com.glodon.paas.activity.resource.internal;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.glodon.paas.activity.api.bean.Activity;
import com.glodon.paas.activity.api.bean.ActivityDefinition;
import com.glodon.paas.activity.api.bean.ActivityIn;
import com.glodon.paas.activity.biz.ActivityBiz;
import com.glodon.paas.activity.biz.ActivityDefinitionBiz;
import com.glodon.paas.activity.dao.domain.ActivityDefinitionEntity;
import com.glodon.paas.activity.dao.domain.ActivityEntity;
import com.glodon.paas.activity.util.ActivityDefinitionHelp;
import com.glodon.paas.activity.util.ActivityTemplateMerger;
import com.glodon.paas.activity.util.NumberUtil;
import com.glodon.paas.util.DateUtil;

@Component
@Path("/internal")
public class ActivityInternalResource {

    private static Logger LOGGER = LoggerFactory.getLogger(ActivityInternalResource.class);
    @Autowired
    ActivityBiz           activityEntityBiz;
    @Autowired
    ActivityDefinitionBiz activityDefinitionBiz;

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/addDefinition")
    public ActivityDefinition addDefinition(
                              @Context HttpServletRequest request, 
                              ActivityDefinition dto
                              ) {
        if (dto.getDefaultReceiver() == null) {
            dto.setDefaultReceiver(NumberUtil.array2long(dto.getDefaultReceivers()));
        }
        if (dto.getNoticeChannel() == null) {
            dto.setNoticeChannel(NumberUtil.array2long(dto.getNoticeChannels()));
        }

        ActivityDefinitionEntity domain = ActivityDefinitionHelp.toActivityDefinitionEntity(dto);
        domain = activityDefinitionBiz.insert(domain);
        return ActivityDefinitionHelp.toActivityDefinition(domain);
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/deleteDefinition")
    public int deleteDefinition(
               @Context HttpServletRequest request,
               @QueryParam("activityType") Long activityType
               ) {
        return activityDefinitionBiz.deleteById(activityType);
    }

    /**
     * update成功，返回最终对应的值，失败返回null
     * 
     * @param request
     * @param dto
     * @return
     */
    public ActivityDefinition updateDefinition(
                              @Context HttpServletRequest request,
                              ActivityDefinition dto
                              ) {
        if (dto.getDefaultReceiver() == null) {
            dto.setDefaultReceiver(NumberUtil.array2long(dto.getDefaultReceivers()));
        }
        if (dto.getNoticeChannel() == null) {
            dto.setNoticeChannel(NumberUtil.array2long(dto.getNoticeChannels()));
        }

        ActivityDefinitionEntity domain = ActivityDefinitionHelp.toActivityDefinitionEntity(dto);

        if (activityDefinitionBiz.update(domain) > 0) {
            domain = activityDefinitionBiz.getByActivityType(domain.getActivityType());
        } else {
            domain = null;
        }

        return ActivityDefinitionHelp.toActivityDefinition(domain);
    }

    public ActivityDefinition getDefinition(
                              @Context HttpServletRequest request,
                              @QueryParam("activityType") Long activityType
                              ) {
        ActivityDefinitionEntity domain = activityDefinitionBiz.selectById(activityType);
        return ActivityDefinitionHelp.toActivityDefinition(domain);
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("")
    public void publish(
                       // @Context HttpServletRequest request,
                       // @Context HttpServletResponse response,
                       // @QueryParam("appId") Integer appId,
                       // @QueryParam("moduleId") Integer moduleId,
                       ActivityIn activityIn) {

        ActivityEntity entity = new ActivityEntity();

        entity.setActorId(activityIn.getActorId());
        entity.setActorName(activityIn.getActorName());

        entity.setAppId(activityIn.getAppId());
        entity.setModuleId(activityIn.getModuleId());
        entity.setActivityType(activityIn.getActivityType());

        entity.setItemId(activityIn.getItemId());
        entity.setItemName(activityIn.getItemName());
        entity.setSubItemId(activityIn.getSubItemId());
        entity.setSubItemName(activityIn.getSubItemName());

        entity.setItemType(activityIn.getItemType());
        entity.setTitle(activityIn.getItemId());
        entity.setContent(activityIn.getContent());

        entity.setPublishTime(activityIn.getPublishTime());

        entity.setExt1(activityIn.getExt1());
        entity.setExt2(activityIn.getExt2());
        //entity.setExtension(activityIn.getExtension());

        activityEntityBiz.publish(entity, activityIn.getReceiverIds());
    }

    /**
     * 参数说明参见ActivityBiz.select
     * 
     * @return
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("")
    public List<ActivityEntity> select(
               @Context HttpServletRequest request,
               @QueryParam("receiverId") String receiverId,
               @QueryParam("appId") String appId,
               @QueryParam("moduleId") String moduleId,
               @QueryParam("activityType") String activityType,
               @QueryParam("itemId") String itemId,
               @QueryParam("itemType") String itemType,
               @QueryParam("subItemId") String subItemId,
               @QueryParam("actorId")String actorId,
               @QueryParam("nearerTime") @DefaultValue("0") String nearerTime, // receiveTime毫秒
               @QueryParam("olderTime") @DefaultValue("0") String olderTime, // receiveTime毫秒
               @QueryParam("needRender")@DefaultValue("false") String needRender,
               @QueryParam("count") @DefaultValue("50") String count
               ) { 
        LOGGER.debug("select()");
        long begin = System.currentTimeMillis();

        Map<String, String> params = new HashMap<String, String>();
        params.put("receiverId", receiverId);
        params.put("appId", appId);
        params.put("moduleId", moduleId);
        params.put("activityType", activityType);
        params.put("itemId", itemId);
        params.put("itemType", itemType);
        params.put("subItemId", subItemId);
        params.put("actorId", actorId);
        params.put("nearerTime", nearerTime);
        params.put("olderTime", olderTime);
        params.put("needRender", needRender);
        params.put("count", count);

        List<ActivityEntity> ls = activityEntityBiz.query(params);

        long end = System.currentTimeMillis();
        LOGGER.debug("time=" + (end - begin));
        return ls;
    }

    /**
     * 模版测试接口
     * 
     * @param template
     * @param activity
     * @return
     */
    public String testTemplate(String template, Activity activity) {
        return ActivityTemplateMerger.mergeTemplate(activity, template);
    }

    // http://127.0.0.1:8080/activity/api/internal/serverinfo?testString=111
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/serverinfo")
    public Object serverinfo(
                  @Context HttpServletRequest request,
                  @Context HttpServletResponse response,
                  @QueryParam("testString") String testString
                  ) {

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("version", "activicy-1.0.0 ");
        param.put("submitDate", "2012-12-04");
        param.put("currentTime", DateUtil.formatDate(new Date(), DateUtil.DAFAULT_DATETIME_FORMAT));
        param.put("testString", testString);
        return param;
    }
}
